import React, { Component } from 'react'
import {
    Form,
    Input,
    Tree,
} from 'antd'

import menuList from '../../../config/menuConfig'
import {reqUpdateRole} from '../../../api'

const {Item} = Form
// 增加用户权限的组件
export default class AuthForm extends Component {

    constructor (props) {
        super(props)
        const {menus} = this.props.role
        this.state = {
            treeData: [],
            checkedKeys: menus, // 选中的权限数组
        }

    }

    // 当选中的东西变化时触发回调
    onCheck = checkedKeys => {
        this.setState({checkedKeys})
    }

    // 父组件调用获取menus的数据
    getMenus = () => {
        return this.state.checkedKeys
    }
    
    componentWillMount () {
        const treeData = [{title: '平台权限', key: 'all', children: []}]
        const childrenList = menuList.map(item => {
            if (item.children) {
                const children = item.children.map(
                    cItem => {
                        return {title: cItem.title, key: cItem.key}
                    }
                )
                return {title: item.title, key: item.key, children}
            } else {
                if (item.key === '/home') {
                    return {title: item.title, key: item.key, disableCheckbox: true}
                } else {
                    return {title: item.title, key: item.key}
                }
                
            }
        })
        
        treeData[0].children = childrenList
        this.setState({treeData})
    }

    // 当前组件接收到新参数时在render之前自动调用
    componentWillReceiveProps (nextProps) {
        // 最新的menus数据
        const menus = nextProps.role.menus
        this.setState({checkedKeys:menus})
    }

    render() {
        const {role} = this.props
        
        return (
            <div>
                <Item label='角色名称' wrapperCol={{span: 14}}>
                    <Input value={role.roleName} disabled/>
                </Item>
                <Tree
                    checkable
                    defaultExpandAll={true}
                    checkedKeys={this.state.checkedKeys}
                    // onSelect={onSelect}
                    onCheck={this.onCheck}
                    treeData={this.state.treeData}
                />
            </div>
        )
    }
}
